
bt.module({builder: function(bt) {
    var j$ = jQuery;

    var prepareDataForAllTabs = function(user_id) {
        var url_base = "/u/" + user_id;
        _ajaxGetDetails(url_base + "/friends/", "friends-wrapper");
        _ajaxGetDetails(url_base + "/wishtogos/", "wishtogos-wrapper");
        _ajaxGetDetails(url_base + "/bookmarks/", "bookmarks-wrapper");
    };

    var _ajaxGetDetails = function(url, item_id) {
        j$.ajax({
            url: url,
            success: function(html) {
                j$("#" + item_id).replaceWith(html);
            }
        }).done(function() {
        })
    };

    var loadMoreTrips = function(trip_or_bookmark, count) {
        var target_div = j$("#" + trip_or_bookmark + "-wrapper");
        if (target_div.attr("data-load-flag") == "1") {
            return null;
        }
        target_div.attr("data-load-flag", "1");
        j$('#ajax-more', target_div).show();
        j$('#ajax-more', target_div).css("visibility", "visible");

        j$.ajax({
            url: j$('#user_tabs li.active').attr('data-ajax-url'),
            data: 'count=' + count,
            success: function(html){
                j$("#" + trip_or_bookmark + "-wrapper").replaceWith(html);
                _initTripsPanelEvent(trip_or_bookmark);
            }
        }).done(function() {
            j$('#trips .cover img').load(function() {
                bt.misc.centerAlignImg(j$(this), 155, 205, false);
            });
            j$(window).resize();
        }).always(function() {
            j$("#" + trip_or_bookmark + "-wrapper").attr("data-load-flag", "0")
        });
        return false;
    };

    var loadMoreWishToGo = function(page, callback) {
        if (j$("#wishtogos-wrapper .wish-to-go-list").attr("data-load-flag") == "1") {
            return null;
        }
        j$("#wishtogos-wrapper .wish-to-go-list").attr("data-load-flag", "1");
        j$('#wishtogos-wrapper #ajax-more').show();
        j$('#wishtogos-wrapper #ajax-more').css("visibility", "visible");

        j$.ajax({
            url: j$('#user_tabs li.active').attr('data-ajax-url'),
            data: 'page=' + page,
            success: function(resp){
                if(resp) {
                    j$("#wishtogos-wrapper .wish-to-go-list").append(resp);
                } else {
                    j$("#load-more").slideUp();
                }
            }
        }).always(function() {
            _initWishToGoPanelEvent();
            callback();
        });
        return false;
    };

    var _ellipsisTripNames = function(target_div) {
        var ellipsis_settings = {
            max_rows: 1,
            alt_text_t: true,
            whole_word: false
        };
        j$(".trip-item .name", target_div).each(function() {
            if (!j$(this).attr("threedots")) {
                j$(this).ThreeDots(ellipsis_settings);
            }
        });
    };

    var _ellipsisCities = function(target_div) {
        var ellipsis_settings = {
            max_rows: 2,
            valid_delimiters: ['•'],
            alt_text_t: true
        };
        // ellipsis sities
        j$(".trip-item .summary .cities", target_div).each(function() {
            if (!j$(this).attr("threedots")) {
                j$(this).ThreeDots(ellipsis_settings);
            }
        });
    };

    var _ellipsisFriendNames = function() {
        var ellipsis_settings = {
            max_rows: 1,
            alt_text_t: true,
            whole_word: false
        };
        j$("#friends-wrapper .friend-item .username").each(function() {
            if (!j$(this).attr("threedots")) {
                j$(this).ThreeDots(ellipsis_settings);
            }
        });
    };

    var _ellipsisSiteNames = function() {
        var ellipsis_settings = {
            max_rows: 1,
            alt_text_t: true,
            whole_word: false
        };
        j$("#wishtogos-wrapper .wish-to-go-list .site-item .name").each(function() {
            if (!j$(this).attr("threedots")) {
                j$(this).ThreeDots(ellipsis_settings);
            }
        });
    };

    var _initTripsPanelEvent = function(trip_or_bookmark) {
        if(j$(".new-navigator li#" + trip_or_bookmark).hasClass("active")) {
            var target_div = j$("#" + trip_or_bookmark + "-wrapper");

            j$("#load-more.trips", target_div).click(function() {
                loadMoreTrips(trip_or_bookmark, parseInt(j$("#load-more.trips", target_div).attr("data-count")));
            });

            // recommend .bind() rather than using .mouseover() directly.
            // .bind() could avoid some bubble events from browser.
            /*if (j$.browser.msie && j$.browser.version == 6) {
                j$(".trip-item", target_div).bind("mouseover", function() {
                    j$(this).find(".item-actions-icon").show();
                });
                j$(".trip-item", target_div).bind("mouseleave", function() {
                    j$(this).find(".item-actions-buttons").hide();
                    j$(this).parent().find(".item-actions-icon").hide();
                });
            } else {
                j$(".trip-item", target_div).bind("mouseover", function() {
                    j$(this).find(".item-actions-icon").stop(true, true).show();
                });
                j$(".trip-item", target_div).bind("mouseleave", function() {
                    j$(this).find(".item-actions-buttons").stop(true, true).animate({'width': 'hide'}, 350,
                        function() {
                            j$(this).parent().find(".item-actions-icon").fadeOut();
                        });
                });
            }*/

            j$('.trip-item', target_div).hover(function(){
                j$(this).find('.item-actions-buttons').stop(true, true).animate({'width': 'show'}, 350);
            }, function(){
                j$(this).find('.item-actions-buttons').delay(500).animate({'width': 'hide'}, 350);
            });

            j$('.item-actions-buttons', target_div).hover(function(){
                j$(this).stop(true, true);
            }, function(){
                j$(this).delay(500).animate({'width': 'hide'}, 350);
            });

            j$(".trip-item a.delete").click(function() {
                if(confirm('确定要删除此游记吗？') == false)
                    return false;

                var trip_item = j$(this).parents('li.trip-item');
                trip_item.css('opacity', 0.3);
                j$.ajax({
                    type: 'DELETE',
                    url: j$(this).attr('href'),
                    success: function(resp){
                        if (resp.error) {
                            alert(resp.error);
                        } else {
                            trip_item.slideUp('slow', function() {
                                trip_item.remove();
                                var n = parseInt(j$(".new-navigator li.trip span").text()) - 1;
                                j$(".new-navigator li.trip span").text(n);
                                if(n == 0) {
                                    j$("#trips-wrapper .hint").slideDown("slow");
                                }
                            });
                        }
                    }
                });
                return false;
            });
        }
    };

    var _initWishToGoPanelEvent = function() {
        if(j$(".new-navigator li.wishtogo").hasClass("active")) {
            j$("#load-more.wishtogo").click(function() {
                var _this = this;
                loadMoreWishToGo(parseInt(j$("#load-more.wishtogo").attr("data-page")),
                        function() {
                            j$(_this).remove();
                            j$("#wishtogos-wrapper .wish-to-go-list").attr("data-load-flag", "0");
                        });
            });

            if (j$.browser.msie && j$.browser.version == 6) {
                j$(".site-item", j$("#wishtogos-wrapper")).bind("mouseover", function() {
                    j$(this).find(".close").show();
                });
                j$(".site-item", j$("#wishtogos-wrapper")).bind("mouseleave", function() {
                    j$(this).find(".close").hide();
                });
            }

            j$(".wish-to-go-list .site-item .close").click(function() {
                var obj = j$(this);
                j$.ajax({
                    url: obj.data("url"),
                    type: "POST",
                    success: function() {
                        var item = obj.parents(".site-item");
                        item.slideUp(function() {
                            item.remove();
                            var n = parseInt(j$(".new-navigator li.wishtogo span").text()) - 1;
                            j$(".new-navigator li.wishtogo span").text(n);
                            if(n == 0) {
                                j$("#wishtogos-wrapper .hint").slideDown("slow");
                            }
                        });
                    }
                });
            });
        }
    };

    var _initEvent = function() {
        _initTripsPanelEvent("trips");

        // Navigator events
        j$('.new-navigator li.nav-item').click(function() {
            if (!j$(this).hasClass('active')) {
                var current_tab_id = j$(this).attr("id");
                var target_div = j$("#" + current_tab_id + "-wrapper");
                if (!target_div.hasClass("ajax-content")) {
                    return null;
                }
                j$(this).siblings().removeClass('active');
                j$(this).siblings().removeClass('nav-left-active');
                j$(this).siblings().removeClass('nav-middle-active');
                j$(this).siblings().removeClass('nav-right-active');

                j$(this).addClass('active');
                if(j$(this).hasClass('nav-left')) {
                    j$(this).addClass('nav-left-active');
                } else if(j$(this).hasClass('nav-middle')) {
                    j$(this).addClass('nav-middle-active');
                } else if(j$(this).hasClass('nav-right')) {
                    j$(this).addClass('nav-right-active');
                }

                j$(".ajax-content").each(function() {
                    if (j$(this).hasClass("current")) {
                        j$(this).toggleClass("hidden current");
                    }
                });
                target_div.toggleClass("hidden current");

                if (current_tab_id == "wishtogos") {
                    _ellipsisSiteNames();
                    _initWishToGoPanelEvent();
                } else if (current_tab_id == "friends") {
                    _ellipsisFriendNames();
                } else if (current_tab_id == "bookmarks") {
                    _ellipsisCities(target_div);
                    _ellipsisTripNames(target_div);
                    _initTripsPanelEvent("bookmarks");
                }

                if(j$(".new-navigator .trip").hasClass("active")
                    || j$(".new-navigator .follow").hasClass("active")) {
                    j$("#trips .cover img", target_div).each(function() {
                        bt.misc.centerAlignImg(j$(this), 155, 205, false);
                    });
                }
                j$(window).resize();
            }
            return false;
        });

        j$(".create-trip, .add-photo").fancybox({
            autoSize: true,
            closeBtn: false,
            padding: 0,
            maxWidth: 382,
            helpers: {
                overlay: {
                    opacity: 0.3
                }
            }
        });

        // Add friend events
        if (j$(".friend-status").hasClass("not-friend")) {
            j$(".friend-status").fancybox({
                autoSize: true,
                closeBtn: false,
                padding: 0,
                maxWidth: 382,
                helpers: {
                    overlay: {
                        opacity: 0.3
                    }
                }
            });
        }
        j$("#new-trip-popup .close, #friend-request-popup .close").click(function() {
            j$.fancybox.close();
        });

        var _addOrRemoveFriend = function(url, data) {
            j$(".friend-status").css('opacity', 0.3);
            j$.ajax({
                url: url,
                data: data,
                type: "GET",
                success: function(html){
                    if (j$(".friend-status").hasClass('is-friend')) {
                        j$(".friend-status").removeClass('is-friend');
                        j$(".friend-status").fancybox({
                            autoSize: true,
                            closeBtn: false,
                            padding: 0,
                            maxWidth: 382,
                            helpers: {
                                overlay: {
                                    opacity: 0.3
                                }
                            }
                        });
                        j$(".friend-status").addClass('not-friend');
                        j$(".friend-status").text('加为好友');
                        j$(".message-btn").remove();
                    } else {
                        if(html.status == 0) {
                            j$(".friend-status").removeClass('not-friend');
                            j$(".friend-status").addClass('wait-confirm');
                            j$(".friend-status").text('等待验证');
                            j$("#friend-request-popup .close").click();
                        } else if(html.status == 1){
                            j$(".friend-status").addClass('is-friend');
                            j$(".friend-status").text( '解除好友');
                        } else {
                            alert("发生错误，请先登录。");
                            location.reload();
                        }
                    }
                    j$(".friend-status").css('opacity', 1);
                }
            });
        };

        j$(".is-friend").click(function() {
            if(!j$(this).hasClass("is-friend")) {
                return false;
            }
            var url = '/users/delete_friend/'; 
            var data = j$("form#friend").serialize();
            _addOrRemoveFriend(url, data);
            return false;
        });

        j$(".accept-friend, .reject-friend").live("click", function() {
            j$.ajax({
                url: j$(this).data("url"),
                type: "GET",
                success: function(resp) {
                    if(resp.error) {
                        alert(resp.error);
                    } else {
                        location.reload();
                    }
                }
            });
            return false;
        });

        j$("form#friend").submit(function() {
            var url = '/users/add_friend/';
            var data = j$("form#friend").serialize();
            if (j$("form#friend textarea").val().length > 50){
                alert("好友请求最多只能有50字！");
                return false;
            }
            _addOrRemoveFriend(url, data);
            return false;
        });

    };

    var _popupFillProfile = function() {
        if(!j$(".profile").data("fill-profile")) {
            return;
        }
        var popup = j$("#fill-profile-popup");
        var overlay = j$("#overlay");
        popup.fadeIn();
        overlay.show();
        popup.css({
            "position": "absolute",
            "top": j$("#content .profile .summary .name").offset().top + 54,
            "left": j$("#content .profile .summary .name").offset().left
        });
        j$("#fill-profile-popup .close").click(function() {
            popup.fadeOut();
            overlay.hide();
            j$(".profile .summary a.fill-profile-btn")
                    .fadeIn().css("display", "block");
        });
    };

    j$(document).ready(function() {
        _ellipsisCities(j$("#trips-wrapper"));
        _ellipsisTripNames(j$("#trips-wrapper"));
        _initEvent();
    });

    j$(window).load(function() {
        _popupFillProfile();
        j$('.passport-icons .icon-item .icon img').each(function(){
            bt.misc.centerAlignImg(j$(this), 46, 46, false);
        });
        j$('#trips .cover img').each(function() {
            bt.misc.centerAlignImg(j$(this), 155, 205, false);
        });
        j$(".passport-panel .more-passport").click(function() {
            if(j$(".passport-panel .passport-icons").hasClass("collapsed")) {
                j$(".passport-panel .more-passport-arrow").animate({"rotate": "180deg"});
            } else {
                j$(".passport-panel .more-passport-arrow").animate({"rotate": 0});
            }
            j$(".passport-panel .passport-icons").toggleClass("collapsed");
        });
    });

    var ellipsisStrings = function(target) {
        var target_div = j$("#" + target + "-wrapper");
        _ellipsisTripNames(target_div);
        _ellipsisCities(target_div);
    };

    var ellipsisWishToGoSiteNames = function() {
        _ellipsisSiteNames();
    };

    bt.user.prepareDataForAllTabs = prepareDataForAllTabs;
    bt.user.ellipsisStrings = ellipsisStrings;
    bt.user.ellipsisSiteNames = ellipsisWishToGoSiteNames;
}});

